import { fork } from 'child_process'
import path from 'path'
import KK_IPC_PROTOCOLS from '../ipc/protocol'
import { ScriptResult } from './scriptEngine'
import { ipcMain } from 'electron'
import { log } from 'console'

export default async function installEngine(): Promise<void> {
  // 启动子进程
  const vmProcess = fork(path.join(__dirname, 'engineWorker.js'))

  const executeScript = async (script: string): Promise<ScriptResult> => {
    return new Promise((resolve, reject) => {
      vmProcess.send({
        command: 'execute',
        script
      })
      //监听子进程的退出事件
      vmProcess.on('exit', (code, signal) => {
        console.log(`子进程退出，代码：${code}，信号：${signal}`)
        reject(new Error(`子进程退出，代码：${code}，信号：${signal}`))
      })
      vmProcess.on('message', (msg: any) => {
        log('vmProcess msg:', msg)
        if (msg.command === 'log' && msg.log) {
          ipcMain.emit('log-message', null, msg.log);
        }
        if (msg.success) {
          log('execute result=>:', msg.result)
          resolve(msg)
        } else {
          log('execute error=>:', msg.error)
          reject(new Error(msg.error))
        }
      })
    })
  }

  // 监听前端执行请求
  ipcMain.handle(KK_IPC_PROTOCOLS.SCRIPT_EXECUTE, async (_event, script: string) => {
    log('execute:', script)
    log('vmProcess:', vmProcess.pid)
    // return 'hello world'
    try {
      const result = await executeScript (script)
      log('execute result:', result)
      return result
    } catch (error) {
      log('execute error:', error)
      return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }
    }
  })
}
